<template>
  <div class="content">
    <div class="pageSearchView">
      <!--      <SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch"/>-->
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="设备编码">
          <el-input v-model="searchParam.equipmentCode" placeholder="请输入设备编码" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-tree-select v-model="searchParam.organizationId" :data="workRoomList" check-strictly
                          :props="{ children: 'sonList', label: 'orgName', value: 'id' }" style="width: 200px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="pageTableView">
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="未完成" name="CREATED">

          <div class="pageTableMenuView">
            <div class="pageTableTitle">
              点检列表信息
              <el-icon>
                <house-icon/>
              </el-icon>
            </div>
          </div>
          <Unfinished :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
                      :onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
                      :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"/>
        </el-tab-pane>
        <el-tab-pane label="已完成" name="FINISHED">
          <div class="pageTableMenuView">
            <div class="pageTableTitle">
              列表信息
              <el-icon>
                <house-icon/>
              </el-icon>
            </div>
          </div>
          <Finish :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
                  :onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
                  :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"/>
        </el-tab-pane>

      </el-tabs>

    </div>


  </div>
</template>

<script setup>
import SearchForm from '@/components/SearchForm.vue';
import {useToolData} from '@/hooks/baseData/tooling';
import axiosInstance from "@/utils/http/api";
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus'; // 假设使用 Element Plus
import {computed, onMounted, ref} from 'vue';
import Unfinished from './unfinished.vue'
import Finish from './finish.vue'
import {equipmentAll, equipmentInspectionTaskPage, equipmentInspectionTaskUpdate} from '@/api/device/pointInspection'

const activeName = ref('CREATED')
const searchParam = ref({})
const searchFields = ref([
  {
    name: "code",
    label: "计划编号",
    component: "input",
    placeholder: "",
    class: "!w-[350px]",
  },

])
const pageTotal = ref(0)
const taskNoPage = ref([])
const equipmentData = ref([])
const paginationParams = ref({pageSize: 10, current: 1})

// 缓存键名，基于当前标签页名称
const getCacheKey = (tabName) => `pointInspectionSearch_${tabName}`

onMounted(() => {
  // 从缓存加载搜索参数
  const cachedSearchParams = localStorage.getItem(getCacheKey(activeName.value))
  if (cachedSearchParams) {
    try {
      searchParam.value = JSON.parse(cachedSearchParams)
    } catch (e) {
      console.error('Failed to parse cached search params', e)
      // 如果解析失败，保持searchParam为空对象
    }
  }

  fetchPage()
  fetchAll()
});

const workRoomList = ref([]);//车间

const fetchAll = () => {
  equipmentAll({}).then(res => {
    equipmentData.value = res.data
  })

  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
}

const fetchPage = (params) => {
  equipmentInspectionTaskPage({
    ...paginationParams.value,
    ...searchParam.value,
    status: activeName.value,
    ...params,
    equipmentInspectionType: 2,
    type: 1,
  }).then(res => {
    taskNoPage.value = res.data.records
    pageTotal.value = res.data.total
  })
}

const resetSearch = () => {
  searchParam.value = {}
  // 清除缓存
  localStorage.removeItem(getCacheKey(activeName.value))
  fetchPage()
}

const handleSearch = () => {
  // 将当前搜索参数保存到缓存
  localStorage.setItem(getCacheKey(activeName.value), JSON.stringify(searchParam.value))
  fetchPage()
}

const handleClick = (tab, event) => {
  // 获取当前标签页的缓存键并保存搜索参数
  const currentCacheKey = getCacheKey(activeName.value)
  localStorage.setItem(currentCacheKey, JSON.stringify(searchParam.value))

  // 设置新的活动标签
  const newTabName = tab.props.name
  activeName.value = newTabName

  // 获取新标签页的缓存键
  const newCacheKey = getCacheKey(newTabName)

  // 从新标签页的缓存加载搜索参数
  const cachedSearchParams = localStorage.getItem(newCacheKey)
  if (cachedSearchParams) {
    try {
      searchParam.value = JSON.parse(cachedSearchParams)
    } catch (e) {
      console.error('Failed to parse cached search params for new tab', e)
      // 如果解析失败，保持searchParam为空对象
    }
  } else {
    // 如果新标签页没有缓存，则清空搜索参数
    searchParam.value = {}
  }

  // 使用新标签页的参数获取数据
  fetchPage({status: newTabName})
}

const onSubmit = (params, callback) => {
  equipmentInspectionTaskUpdate(params).then(res => {
    if (res.code === 200) {
      ElMessage.success('任务已完成');
      fetchPage()
      callback();
    } else {
      ElMessage.error(res.message);
    }
  })
}

const handleSizeChange = (val) => {
  paginationParams.value.pageSize = val;
  fetchPage()
}

const handleCurrentChange = (val) => {
  paginationParams.value.current = val;
  fetchPage()
}

</script>

<style scoped></style>